/**
 *功能說明：新增FCN_SERVICE_SUBSCRIBER_TMP 資料 
 *版本異動說明:
 *    Ver      Date          Author            Description
 *    ------   -----------   ---------------   --------------------------------------
 *    1.0     2012/02/12     Jeff Gu        Create FCN_SERVICE_PREPAID
 *@author:  Jeff Gu  	
 *@since JDK 1.6
 *@version 1.0
 */package fet.gw.common.procedure.service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.transaction.xa.Xid;

import org.apache.log4j.Logger;

import fet.gw.common.util.AbstractGWService;
import fet.gw.common.util.BeanUtils;
import fet.gw.common.util.DBUtils;
import fet.gw.common.util.FET_GW_Constants;
import fet.gw.common.util.JavaShellUtil;
import fet.gw.common.util.PropertyUtils;

public class FCN_SERVICE_PREPAID extends AbstractGWService {
	
	
	private static Logger logger = Logger.getLogger(FCN_SERVICE_PREPAID.class);
	
	/**
	 * 程式進入點  傳入時間區間跟帳號密碼
	 * @param args
	 */
	public static void main(String[] args) {
		try{
			if(args.length>2){
				//傳入參數period_from_p,period_to_p
				FCN_SERVICE_PREPAID service_prepaid = new FCN_SERVICE_PREPAID();
				String period_from_p = args[0];
				String period_to_p = args[1];
				logger.debug("period_from_p:"+period_from_p + " period_to_p:"+period_to_p);
				String appsIdAndPwd = args[2];
				if(!appsIdAndPwd.contains(DBUtils.APPS_ID_PWD_SEPARATOR)){
					System.out.println("Apps IdAndPwd must split by "+DBUtils.APPS_ID_PWD_SEPARATOR+".");
					return;
				}
				service_prepaid.process(period_from_p, period_to_p,appsIdAndPwd);
			}else{
				System.out.println("FCN_SERVICE_PREPAID:"+FET_GW_Constants.MIAN_ARGS_NOT_NULL);
			}
		}catch (Exception e) {
			logger.debug("FCN_SERVICE_PREPAID Exception_"+e,e);
		}
	}
	
	/**
	 * 做邏輯處理入口點
	 */
	public void process(String period_from_p , String period_to_p, String appsIdAndPwd){
		Xid xid = null;
		try {
			//建立DB鏈接（Shell 傳入userName and password）
			this.initialDBApps(appsIdAndPwd);

			xid = this.startXAResource(DBUtils.SCHEMA_ALIAS_APPS);
			
			
			//先根據傳入 shell 的period_from_id_p IN NUMBER, period_to_id_p IN NUMBER 
			//從 table cn_periods_all_v取得 start date & end date
		//	Date startDate = getStartDate(period_from_p);
		//	logger.debug("startDate:"+startDate);
		//	Date endDate = getEndDate(period_to_p);
		//	logger.debug("endDate:"+endDate);
			
		//	//刪除Erp table FCN_SERVICE_SUBSCRIBER_TMP 的 舊資料
			this.deleteFCN_SERVICE_SUBSCRIBER_TMP();
			//然後根據 start date & end date 去  subscriber取得資料
			//塞入 erp table FCN_SERVICE_SUBSCRIBER_TMP  為呼叫.prc 做資料的準備 
			List<Object>  ServiceSubscriberTmp = this.list_Fcn_Service_Subscriber_TMP(period_from_p, period_to_p);
			logger.debug("ServiceSubscriberTmp.size():"+ServiceSubscriberTmp.size());
			//新增資料
			this.createFCN_SERVICE_SUBSCRIBER_TMP(ServiceSubscriberTmp);
			//計算新增的記錄數
			this.countFCN_SERVICE_SUBSCRIBER_TMP();
			//jeff test
			this.endXAResource(DBUtils.SCHEMA_ALIAS_APPS, xid);
		} catch (Exception e) {
			//此處的異常不能拋出  需要把Exception 寫進log文件,以便後續當成mail的附件使用
			try {
				if(xid!=null){
					this.endXAResourceAndRollback(DBUtils.SCHEMA_ALIAS_APPS, xid);
				}
				String basePath=JavaShellUtil.executeShell(JavaShellUtil.FCN_TOP_PATH);
				String className = FCNGWRES.class.getSimpleName();
				String fileName = basePath+PropertyUtils.getPara(FET_GW_Constants.LOGFILENAME, className+"."+FET_GW_Constants.ERROR_LOG);
				createLogRecords(fileName,e,FCN_SERVICE_PREPAID.class.getName());
			} catch (Exception e1) {
				logger.error("FCN_SERVICE_PREPAID.process error ", e);
			}
			logger.error("FCN_SERVICE_PREPAID.process error ", e);
		}finally{
			try {
				this.closeDB(DBUtils.SCHEMA_ALIAS_APPS);
			} catch (Exception e) {
				logger.error("FCN_SERVICE_PREPAID.process_ error ", e);
			}
		}
	}	


	/**
	 * list FCN_SERVICE_SUBSCRIBER data by start date and end date
	 * @param startDate
	 * @param endDate
	 * @return List<Object>
	 */
	private List<Object> list_Fcn_Service_Subscriber_TMP(String startDate,String endDate) throws Exception{
		List<Object> fcnServiceSubscriberTmp = new ArrayList<Object>();
		FCN_SERVICE_SUBSCRIBER_TMP fcnServiceSubscriber = null;
		List<Map<String, Object>> result = null;
		try {
            if(startDate != null &&  endDate != null ){
            	
       
            	//--啟用日Monthly
            	String sql ="select count(*) from subscriber " +
            			"where sub_sts_last_act='SL_NEW_SUB_ACTIVATION' " +
            			"and INIT_ACT_DATE between to_date('"+startDate+"', 'YYYY-MM-dd') and to_date('"+endDate+"', 'YYYY-MM-dd') " +
            			" and SUB_STS_RSN_CD='MG19'";
            	
            	logger.debug(sql);
            	//jeff test
				result = findByNativeSql(DBUtils.SCHEMA_ALIAS_FETSCU2,sql,true);
				logger.debug("result:"+result);
			}
			if(result!=null){
	    		for(Map<String, Object> ColumnValueMaping : result){
	    			fcnServiceSubscriber = (FCN_SERVICE_SUBSCRIBER_TMP) BeanUtils.copyMapToBean(FCN_SERVICE_SUBSCRIBER_TMP.class, ColumnValueMaping);
	    			fcnServiceSubscriberTmp.add(fcnServiceSubscriber);
	    		}
	    	}
		} catch (Exception e) {
			logger.error("FCN_SERVICE_SUBSCRIBER.list_Fcn_Service_Subscriber error ", e);
			throw e;
		}
		return fcnServiceSubscriberTmp;
	}
	/**
	 * 清空temp table中的所有記錄
	 * */
	private void deleteFCN_SERVICE_SUBSCRIBER_TMP() throws Exception{
		try {
			String sql = "delete from FCN_SERVICE_SUBSCRIBER_TMP";
			updateByNativeSql(DBUtils.SCHEMA_ALIAS_APPS,sql);
		} catch (Exception e) {
			logger.error("FCNGWRES.deleteFCN_SERVICE_SUBSCRIBER error ", e);
			throw e;
		}
	}	
	/**
	 * save FCN_SERVICE_SUBSCRIBER to temp table 
	 * @param FCN_SERVICE_SUBSCRIBER
	 */
	private void createFCN_SERVICE_SUBSCRIBER_TMP(List<Object> FCN_SERVICE_SUBSCRIBER) throws Exception{
		try {
			insertAll(DBUtils.SCHEMA_ALIAS_APPS,FCN_SERVICE_SUBSCRIBER,"FCN_SERVICE_SUBSCRIBER_TMP");
		} catch (Exception e) {
			logger.error("FCNGWRES.createFCN_SERVICE_SUBSCRIBER error ", e);
			throw e;
		}finally{
		}
	}
	
	/**
	 * 取得匯入資料的筆數
	 * @author leoren
	 * @throws Exception
	 */
	public void countFCN_SERVICE_SUBSCRIBER_TMP() throws Exception{
		List<Map<String, Object>> result = null;
		try{
			StringBuffer sql = new StringBuffer();
			sql.append(" select count(*) as IEXISTCOUNT from  FCN_SERVICE_SUBSCRIBER_TMP ");
			logger.debug(sql.toString());
			result = findByNativeSql(DBUtils.SCHEMA_ALIAS_APPS,sql.toString());
			int iExistCount = 0;
			if(result!=null){
				for(Map<String, Object> ColumnValueMaping : result){
					if(ColumnValueMaping.get("IEXISTCOUNT")!=null){
						iExistCount = Integer.valueOf(ColumnValueMaping.get("IEXISTCOUNT").toString());
					}
	    		}
	    	}
			System.out.println(FET_GW_Constants.IMPORTMESSAGE+iExistCount);
		}catch(Exception e){
			logger.error("FCNGWRES.countFCN_SERVICE_SUBSCRIBER_TMP"+FET_GW_Constants.EXCE_FAIL+e.toString(),e);
			throw e;
		}
	}

	

}
